package microservices

import (
	"github.com/flairamos/go-component/nacos"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"gopkg.in/yaml.v2"
	"kuangstudy-mall/srvs/user-srv/global"
	"kuangstudy-mall/srvs/user-srv/initialize"
)

func NacosUserSrvConfig() {

	contextPath := "/nacos"
	scheme := "http"
	instance := &nacos.NacosInstance{
		IpAddr:      &global.ServerConfig.NacosInfo.Host,
		Port:        &global.ServerConfig.NacosInfo.Port,
		Username:    &global.ServerConfig.NacosInfo.User,
		Password:    &global.ServerConfig.NacosInfo.Password,
		Scheme:      &scheme,
		ContextPath: &contextPath,
	}

	config := nacos.DefaultClient(global.ServerConfig.NacosInfo.Namespace,
		global.ServerConfig.NacosInfo.Dataid,
		global.ServerConfig.NacosInfo.GroupId, instance)
	err := nacos.GetRemoteConfig(config, &global.ServerConfig)
	if err != nil {
		panic(err)
	}

	client, _ := nacos.ConfigClient(config)
	err2 := client.ListenConfig(vo.ConfigParam{
		DataId: global.ServerConfig.NacosInfo.Dataid,
		Group:  global.ServerConfig.NacosInfo.GroupId,
		OnChange: func(namespace, group, dataId, data string) {
			yaml.Unmarshal([]byte(data), &global.ServerConfig)
			// 初始化数据库连接
			initialize.InitDB()
		},
	})
	if err2 != nil {
		panic(err)
	}
}
